package com.le.buddha.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.nls.client.AccessToken;
import com.le.buddha.conf.RedisKey;
import com.le.buddha.service.IWeChatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Service
public class WeChatServiceImpl implements IWeChatService {
    @Value("${wx.appid}")
    private String appid;

    @Value("${wx.appsecret}")
    private String appsecret;
    @Resource
    private RedisTemplate<String, String> template;
    @Override
    public synchronized String getAccessToken() {
        String wechatToken = template.opsForValue().get(RedisKey.wechatToken);
        //            if( Boolean.FALSE.equals(redisTemplate.hasKey(RedisKey.aliyuntoken))){
        if (ObjectUtil.isNull(wechatToken)) {
            Map<String,Object> param=new HashMap<>();
            param.put("grant_type","client_credential");
            param.put("appid",appid);
            param.put("secret",appsecret);
            JSONObject result= JSONUtil.parseObj(HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token",param)) ;
            wechatToken=result.getStr("access_token");
            Integer expiresIn=result.getInt("expires_in")-1000;
            template.opsForValue().set(RedisKey.wechatToken, wechatToken, expiresIn, TimeUnit.MICROSECONDS);

            return wechatToken;
        } else {
             return wechatToken;
        }


    }

    @Override
    public String getOpenId(String code) {
        Map<String,Object> param=new HashMap<>();
        param.put("grant_type","client_credential");
        param.put("appid",appid);
        param.put("secret",appsecret);
        param.put("js_code",code);
        JSONObject result= JSONUtil.parseObj(HttpUtil.get("https://api.weixin.qq.com/sns/jscode2session",param)) ;
        return result.getStr("openid");
    }
}
